import * as PIXI from 'pixi.js'
import { watch, Ref } from 'vue'
import useMainStore from '@/store/modules/useMainStore'
import { useFocus } from '@vueuse/core'

export default async (inputRef: Ref<HTMLInputElement>, fontSize: number) => {
  const mainStore = useMainStore()
  const app = await mainStore.getApp()
  // 光标
  const cursor = new PIXI.Text({
    text: '丨',
    style: {
      fontFamily: 'Arial',
      fontSize,
      fill: 0x111111,
      align: 'center',
    },
  })
  cursor.alpha = 0
  cursor.anchor.set(0.5, 0)
  // 光标闪烁
  const flicker = (cursor: PIXI.Text) => {
    let coefficient = -1
    return (time: PIXI.Ticker) => {
      if (cursor.alpha >= 2) {
        coefficient = -1
      } else if (cursor.alpha <= -3) {
        coefficient = 1
      }
      cursor.alpha += coefficient * time.deltaTime * 0.1
    }
  }
  const flickerTicker = flicker(cursor)
  const { focused } = useFocus(inputRef) // 输入框是否聚焦
  watch(focused, () => {
    if (focused.value) {
      cursor.alpha = 1
      app.ticker.add(flickerTicker)
    } else {
      cursor.alpha = 0
      app.ticker.remove(flickerTicker)
    }
  })
  return {
    cursor,
    focused,
  }
}
